package com.ctshk.rpc.season.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SeasonType;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.bus.dto.BusPriceRemainderDTO;
import com.ctshk.rpc.bus.service.IBusProductService;
import com.ctshk.rpc.season.dto.PackageProductCostDTO;
import com.ctshk.rpc.season.dto.SeasonFixedProductPackageBusDTO;
import com.ctshk.rpc.season.entity.SeasonFixedProductPackageBus;
import com.ctshk.rpc.season.mapper.SeasonFixedProductPackageBusMapper;
import com.ctshk.rpc.season.req.PassengerReq;
import com.ctshk.rpc.season.req.SeasonFixedProductPackageBusReq;
import com.ctshk.rpc.season.req.UpdatePackageProductReq;
import com.ctshk.rpc.season.service.ISeasonFixedProductPackageBusService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套票-固定套票单项产品打包-巴士表 服务实现类
 * </p>
 *
 * @author 杨林
 * @since 2021-03-09
 */
@DubboService
public class SeasonFixedProductPackageBusServiceImpl extends ServiceImpl<SeasonFixedProductPackageBusMapper, SeasonFixedProductPackageBus> implements ISeasonFixedProductPackageBusService {

    @Autowired
    private SeasonFixedProductPackageBusMapper seasonFixedProductPackageBusMapper;

    @DubboReference
    private IBusProductService busProductService;


    /* @MethodName: 获取巴士票的价格
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/26 17:09
     **/
    @Override
    public PackageProductCostDTO getBusProductPrice(Long productId, LocalDate departDate, Long userId, Integer channelType) {
        PackageProductCostDTO costDTO = new PackageProductCostDTO();
        try {
            BusPriceRemainderDTO result = busProductService.findBusSalePriceInfoHandle(channelType, productId, departDate, userId);
            if (null != result) {
                if (0 == result.getIsLimitTicket() || result.getRemainderNumber() > 0) {
                    costDTO.setCostPrice(result.getAdultPrice());
                    costDTO.setChildPrice(result.getChildrenPrice());
                    costDTO.setStock(result.getRemainderNumber());
                }
            }
        } catch (Exception e) {
            log.error("调用巴士服务获取价格发生异常", e);
        }
        return costDTO;
    }

    /* @MethodName: 获取 固定套票默认巴士的价格
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/18 18:04
     **/
    @Override
    public BigDecimal getDefaultBusPrice(Long packageId, LocalDate departDate, LocalDate arrDate, Long userId, Integer channelType) {
        BigDecimal bd = BigDecimal.ZERO;
        //获取默认的 巴士产品 有返还
        List<SeasonFixedProductPackageBus> resultList = seasonFixedProductPackageBusMapper.selectList(
                new QueryWrapper<SeasonFixedProductPackageBus>().lambda().
                        eq(SeasonFixedProductPackageBus::getIsDefault, SeasonType.YES_DEFAULT.getCode()).
                        eq(SeasonFixedProductPackageBus::getIsDeleted, IsDeletedCode.NO.getCode()).
                        eq(SeasonFixedProductPackageBus::getPackageId, packageId)
        );
        boolean departFlag = true;
        boolean returnFlag = true;
        if (null != resultList && resultList.size() > 0) {
            for (SeasonFixedProductPackageBus result : resultList) {
                if (departFlag && SeasonType.JOURNEY_TYPE_DEPART.getKey().equals(result.getTripType())) {
                    bd.add(getBusProductPrice(result.getProductId(), departDate, userId, channelType).getCostPrice());
                    departFlag = false;
                }
                if (returnFlag && SeasonType.JOURNEY_TYPE_RETURN.getKey().equals(result.getTripType())) {
                    bd.add(getBusProductPrice(result.getProductId(), arrDate, userId, channelType).getCostPrice());
                    returnFlag = false;
                }
            }
        }
        return bd;
    }

    @Override
    public List<SeasonFixedProductPackageBusDTO> getBusByPackageId(Long packageId, LocalDate departDate, LocalDate arrDate, Long userId, Integer channelType) {
        List<SeasonFixedProductPackageBus> resultList = seasonFixedProductPackageBusMapper.selectList(
                new QueryWrapper<SeasonFixedProductPackageBus>().lambda().
                        eq(SeasonFixedProductPackageBus::getIsDeleted, IsDeletedCode.NO.getCode()).
                        eq(SeasonFixedProductPackageBus::getPackageId, packageId)
        );
        List<SeasonFixedProductPackageBusDTO> resultDtoList = new ArrayList<>();
        if (null != resultList && resultList.size() > 0) {
            for (SeasonFixedProductPackageBus result : resultList) {
                SeasonFixedProductPackageBusDTO resultDto = EntityUtil.copy(result, SeasonFixedProductPackageBusDTO.class);
                if (SeasonType.JOURNEY_TYPE_DEPART.getKey().equals(result.getTripType())) {
                    resultDto.setCost(getBusProductPrice(result.getProductId(), departDate, userId, channelType).getCostPrice());
                }
                if (SeasonType.JOURNEY_TYPE_RETURN.getKey().equals(result.getTripType())) {
                    resultDto.setCost(getBusProductPrice(result.getProductId(), arrDate, userId, channelType).getCostPrice());
                }
                resultDtoList.add(resultDto);
            }
        }
        return resultDtoList;
    }

    /* @MethodName: 批量保存 巴士车票信息
     * @Description: TODO
     * @Param: userId 用户id ，productId 产品id packageId  打包Id
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/9 17:25
     **/
    @Override
    public void batchBusProduct(Long userId, Long packageId, List<SeasonFixedProductPackageBusReq> busReqList) {
        LocalDateTime now = LocalDateTime.now();
        List<SeasonFixedProductPackageBus> busList = busReqList.stream().map(
                busReq -> {
                    SeasonFixedProductPackageBus bus = EntityUtil.copy(busReq, SeasonFixedProductPackageBus.class);
                    bus.setCreateId(userId);
                    bus.setPackageId(packageId);
                    bus.setGmtCreate(now);
                    bus.setId(IdWorker.getId());
                    bus.setIsDeleted(IsDeletedCode.NO.getCode());
                    return bus;
                }
        ).collect(Collectors.toList());

        seasonFixedProductPackageBusMapper.insertBatchSomeColumn(busList);
    }


    /* @MethodName: 获取固定产品 巴士票产品 信息
     * @Description: TODO
     * @Param: fixedSeasonId 固定套票id   packageId 产品打包id
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/11 11:40
     **/
    @Override
    public List<SeasonFixedProductPackageBusDTO> getSeasonFixedProductBusDtoList(Long packageId) {
        List<SeasonFixedProductPackageBus> productPackageBusList = getSeasonFixedProductBusList(packageId);
        List<SeasonFixedProductPackageBusDTO> list = new LinkedList<>();
        if (null != productPackageBusList && productPackageBusList.size() > 0) {
            list = productPackageBusList.stream().map(
                    bus -> {
                        SeasonFixedProductPackageBusDTO busDto = EntityUtil.copy(bus, SeasonFixedProductPackageBusDTO.class);
                        return busDto;
                    }
            ).collect(Collectors.toList());
        }
        return list;
    }

    /* @MethodName: 修改 固定套票的时候 删除之前的 巴士票产品
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/12 16:28
     **/
    @Override
    public void deletePreviousBus(Long userId, Long packageId) {
        LocalDateTime now = LocalDateTime.now();
        UpdateWrapper<SeasonFixedProductPackageBus> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("modified_id", userId);//修改人
        updateWrapper.set("is_deleted", IsDeletedCode.YES.getCode());//删除
        updateWrapper.set("gmt_modified", now);//修改时间
        updateWrapper.eq("package_id", packageId);
        seasonFixedProductPackageBusMapper.update(null, updateWrapper);

    }


    /* @MethodName: 获取巴士票 差价信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/23 10:31
     **/
    @Override
    public List<SeasonFixedProductPackageBusDTO> getBusDifferencePrice(UpdatePackageProductReq req) {
        Long packageId = req.getPackageId();
        String journeyType = req.getJourneyType();//行程类型
        //查询日期 当是返程的时候 用结束日期
        LocalDate queryDate = req.getStartDate();
        if (SeasonType.JOURNEY_TYPE_RETURN.getKey().equals(journeyType)) {
            queryDate = req.getEndDate();
        }
        List<SeasonFixedProductPackageBusDTO> list = new LinkedList<>();
        SeasonFixedProductPackageBusDTO busDTO = getSeasonFixedDefaultProductBus(packageId, journeyType, queryDate, req.getPassengerReqList(), req.getUserId());
        list.add(busDTO);
        BigDecimal flagCost = busDTO.getCost();
        List<SeasonFixedProductPackageBus> busList = getSeasonFixedProductBusList(packageId, journeyType);
        LocalDate finalQueryDate = queryDate;
        busList.stream().forEach(
                bus -> {
                    Long shipProductId = bus.getProductId();
                    SeasonFixedProductPackageBusDTO busDto = EntityUtil.copy(bus, SeasonFixedProductPackageBusDTO.class);
                    PackageProductCostDTO busCost = getBusProductPrice(shipProductId, finalQueryDate, req.getUserId(), 1);
                    busDto.setCost(busCost.getCostPrice());
                    if (BigDecimal.ZERO.compareTo(busDTO.getCost()) == 0) {//表示没有库存
                        busDto.setPriceDifference("售罄");
                    } else {
                        busDto.setPriceDifference(String.valueOf(flagCost.subtract(busDTO.getCost())));//减法
                    }
                    list.add(busDto);
                });
        return list;
    }


    /* @MethodName: 获取 不是默认 的巴士产品信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/23 10:20
     **/
    private List<SeasonFixedProductPackageBus> getSeasonFixedProductBusList(Long packageId, String journeyType) {
        List<SeasonFixedProductPackageBus> list = seasonFixedProductPackageBusMapper.selectList(
                new QueryWrapper<SeasonFixedProductPackageBus>().lambda()
                        .eq(SeasonFixedProductPackageBus::getPackageId, packageId)
                        .eq(SeasonFixedProductPackageBus::getTripType, journeyType)
                        .eq(SeasonFixedProductPackageBus::getIsDeleted, IsDeletedCode.NO.getCode())
                        .eq(SeasonFixedProductPackageBus::getIsDefault, SeasonType.NO_DEFAULT.getCode())
        );
        return list;

    }

    /* @MethodName: 获取默认的 bus 票信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/23 10:32
     **/
    public SeasonFixedProductPackageBusDTO getSeasonFixedDefaultProductBus(Long packageId, String journeyType, LocalDate queryDate, List<PassengerReq> passengerReqList, Long userId) {
        SeasonFixedProductPackageBus bus = seasonFixedProductPackageBusMapper.selectOne(
                new QueryWrapper<SeasonFixedProductPackageBus>().lambda()
                        .eq(SeasonFixedProductPackageBus::getPackageId, packageId)
                        .eq(SeasonFixedProductPackageBus::getTripType, journeyType)
                        .eq(SeasonFixedProductPackageBus::getIsDeleted, IsDeletedCode.NO.getCode())
                        .eq(SeasonFixedProductPackageBus::getIsDefault, SeasonType.YES_DEFAULT.getCode())
        );
        SeasonFixedProductPackageBusDTO busDTO = EntityUtil.copy(bus, SeasonFixedProductPackageBusDTO.class);

        PackageProductCostDTO busCost = getBusProductPrice(bus.getProductId(), queryDate, userId, 1);
        busDTO.setCost(busCost.getCostPrice());
        if (BigDecimal.ZERO.compareTo(busDTO.getCost()) == 0) {//表示没有库存
            busDTO.setPriceDifference("售罄");
        } else {
            busDTO.setPriceDifference("0");
        }
        return busDTO;
    }


    /* @MethodName: 获取固定产品 巴士票产品 信息
     * @Description: TODO
     * @Param: fixedSeasonId 固定套票id   packageId 产品打包id
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/11 11:40
     **/
    private List<SeasonFixedProductPackageBus> getSeasonFixedProductBusList(Long packageId) {
        QueryWrapper<SeasonFixedProductPackageBus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("package_id", packageId);
        queryWrapper.eq("is_deleted", IsDeletedCode.NO.getCode());
        return seasonFixedProductPackageBusMapper.selectList(queryWrapper);
    }
}
